package com.shooter.utils;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MathUtil {
    public static final String NUMERIC = "1234567890";
    public static final String LETTER = "abcdefghijklmnopqrstuvwxyz1234567890";

    //保留两位小数
    public static String fromTowDecimal(float f) {
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(f);
    }

    //保留一位小数
    public static String fromOnDecimal(float f) {
        DecimalFormat df = new DecimalFormat("#0.0");
        return df.format(f);
    }

    /**
     * 获取随机指定范围字符串
     *
     * @param strType
     * @param initStr 随机数前缀 不需要可为空
     * @param length  随机数长度
     * @return
     */
    public static String getRandLetter(String strType, String initStr, int length) {
        initStr = initStr == null ? "" : initStr;
        StringBuilder txSecret = new StringBuilder();
        txSecret.append(initStr);
        for (int i = 0; i < length; i++) {
            int r = (int) (Math.random() * strType.length());
            txSecret.append(strType.substring(r, r + 1));
        }
        return txSecret.toString();
    }

    /**
     * 获取随机数
     *
     * @param initStr 前置字符
     * @param length  随机数长度
     * @return
     */
    public static String getSum(String initStr, int length) {
        String sum = "";
        for (int i = 0; i < length; i++) {
            sum += "" + (int) (Math.random() * 10);
        }
        return (initStr == null ? "" : initStr) + sum;
    }

    //获取随机字符（包含数字和字母）
    public static String getRandLetter(String initStr, int length) {
        return getRandLetter(LETTER, initStr, length);
    }

    //获取随机字符（包含数字和字母）
    public static String getRandLetter(int length) {
        return getRandLetter(LETTER, "", length);
    }

    //是否數字 包括负数
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^[0-9]+(.[0-9]+)?$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches() || str.trim().equals("")) {
            return false;
        }
        return true;
    }
}
